/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.*;
/**
 *
 * @author Alberto
 */
@WebServlet(name = "Gestion", urlPatterns = {"/Gestion"})
public class Gestion extends HttpServlet {
    @Resource(name = "jdbc/Tienda_bfernandezo_asanchezoliv")
    private DataSource ds;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            
            out.println("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
            out.println("<html xmlns='http://www.w3.org/1999/xhtml'>");
            out.println("<head>");
            out.println("<link href='styles/styles.css' rel='stylesheet' type='text/css'>");
            out.println("<title>Gestion</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1 id='titulo'>Alta Producto En ca' Paqui</h1>");
            out.println("<a class='Inicio' href='/Tienda_bfernandezo_asanchezoliv/'><font size='6' color='black'>Inicio</font></a>");
            out.println("<a class='  Volver' href='/Tienda_bfernandezo_asanchezoliv/Administrador'><font size='6' color='black'>Volver</font></a>");
            out.println("<div class='AltaP'>");
            out.println("<form method='post' action='/Tienda_bfernandezo_asanchezoliv/Gestion'>");
            out.println("ID Producto: <input type='text' name='idProducto' /><br/>");
            out.println("ID Familia: <input type='text' name='idFamilia' /><br/>");
            out.println("Nombre: <input type='text' name='nombre' /><br/>");
            out.println("Descripcion: <input type='text' name='descripcion' /><br/>");
            out.println("Precio: <input type='text' name='precio' /><br/>");
            out.println("Stock: <input type='text' name='stock' /><br/>");
            out.println("Fecha Alta(dd/MM/yy): <input type='text' name='fechaAlta' /><br/>");
            out.println("Nombre Imagen: <input type='text' name='imagen' /><br/>");
            out.println("<input type='submit' name='Añadir' value='Añadir' class='boton_añadir'>"); 
            out.println("</form>");
            
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Gestion</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Gestion at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean error = false;
        Tienda tienda = Tienda.getInstancia(ds);
        try{
            int idp = Integer.parseInt(request.getParameter("idProducto"));
            int idf = Integer.parseInt(request.getParameter("idFamilia"));
            String nombre = request.getParameter("nombre");
            String descripcion = request.getParameter("descripcion");
            float precio = Float.parseFloat(request.getParameter("precio"));
            int stock = Integer.parseInt(request.getParameter("stock"));
            String fechaAux = request.getParameter("fechaAlta");
            fechaAux = fechaAux.replaceAll("/", "-");
            Date fecha = Date.valueOf(fechaAux);
            String imagen = request.getParameter("imagen");
            Producto producto = new Producto(idp, idf, nombre, descripcion, precio, stock, fecha, imagen);
            int mod = -1;
            
            try{
                mod = Integer.parseInt(request.getParameter("mod"));
            }catch(Exception e){mod = -1;}
            
            if (mod == -1)
                tienda.añadirProducto(producto);
            else
                tienda.modificarProducto(producto);
  
        }catch(Exception e){System.err.println("Gestion-->DoGet | " + e.getMessage()); error = true;}
        
        if (error)
            request.setAttribute("error", 1);
        String destination = "/admin.jsp";
        forwardToPage(request, response, destination);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private void forwardToPage(final HttpServletRequest request, 
                           final HttpServletResponse response,
                           String url) throws IOException, ServletException
    {
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
      dispatcher.forward(request,response);
    }
    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
